package doan.chuyennganh.activity;

import java.util.ArrayList;

import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import doan.chuyennganh.base.DoAnBaseAcitvity;
import doan.chuyennganh.model.ClassStudent;
import doan.chuyennganh.model.ListClass;
import doan.chuyennganh.model.ListStudent;
import doan.chuyennganh.model.ListStudentReturnObject;
import doan.chuyennganh.model.Student;
import doan.chuyennganh.util.Constants;
import doan.chuyennganh.util.ListStudentDataSource;

@SuppressWarnings("deprecation")
public class SlidingActivity extends SlidingMenuActivity {

	private LayoutInflater inflater;
	public View view;
	private ArrayList<ClassStudent> listClass;
	private int selectedClass = 0;
	private Button btnLogout;
	public static TabHost tabHost;
	public static LocalActivityManager mLocalActivityManager;
	public static DoAnBaseAcitvity currentTabActivity;

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(android.R.style.Theme_Holo_NoActionBar);
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		if (intent != null) {
			try {
				Bundle data = intent.getExtras();
				if (data != null) {
					listClass = (ArrayList<ClassStudent>) data
							.getSerializable(Constants.KEY_LIST_CLASS);
					ListClass.getInstance().setList(listClass);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		btnLogout = (Button) findViewById(R.id.logout_menu);
		tabHost = (TabHost) findViewById(android.R.id.tabhost);

		mLocalActivityManager = new LocalActivityManager(this, false);
		mLocalActivityManager.dispatchCreate(savedInstanceState);
		mLocalActivityManager.dispatchResume();
		mLocalActivityManager.dispatchPause(isFinishing());
		tabHost.setup(mLocalActivityManager);
		tabHost.getTabWidget().setDividerDrawable(null);
		if (listClass.size() <= 0) {
			tabHost.getTabWidget().setEnabled(false);
			TextView tv = ((TextView) findViewById(R.id.tab_title));
			tv.setText(getString(R.string.txt_disable_tabhost));
			tv.setTextColor(ColorStateList.valueOf(R.color.Red));
		} else {
			((TextView) findViewById(R.id.tab_title)).setText(listClass.get(
					selectedClass).getTenmonhoc()
					+ "\n" + listClass.get(selectedClass).getMalop());
			ListStudentDataSource clshelper = new ListStudentDataSource(this,
					listClass.get(selectedClass).getMalop());
			clshelper.open();
			ListStudent.getInstance().setList(
					(ArrayList<Student>) clshelper.getAllStudents());
			ListStudent.getInstance().setClassID(
					listClass.get(selectedClass).getMalop());
			ListStudent.getInstance().setAttendanceList(
					clshelper.getAllttendances());
			clshelper.close();
		}
		// Tab for Home
		Intent homeIntent = new Intent(getApplicationContext(),
				HomeActivity.class);
		homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		addTab(R.string.txt_home, R.drawable.home, homeIntent);

		// Tab for Scanner
		Intent scannerIntent = new Intent(getApplicationContext(),
				ScannerActivity.class);
		scannerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		addTab(R.string.txt_scanner, R.drawable.scan, scannerIntent);

		// Tab for list student
		Intent liststIntent = new Intent(getApplicationContext(),
				ListStudentActivity.class);
		liststIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		addTab(R.string.txt_list, R.drawable.list_icon, liststIntent);

		// Tab for export to excel file
		Intent exportIntent = new Intent(getApplicationContext(),
				ExportActivity.class);
		exportIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		addTab(R.string.txt_export, R.drawable.icon_excel, exportIntent);

		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				if (tabHost.getCurrentView().getContext() instanceof DoAnBaseAcitvity) {
					currentTabActivity = (DoAnBaseAcitvity) tabHost
							.getCurrentView().getContext();
				}
				if (tabId.equals(getString(R.string.txt_home))) {
					setMenu(Menu.HOME);

				} else if (tabId.equals(getString(R.string.txt_scanner))) {
					setMenu(Menu.SCANNER);

				} else if (tabId.equals(getString(R.string.txt_list))) {
					setMenu(Menu.LIST);

				} else if (tabId.equals(getString(R.string.txt_export))) {
					setMenu(Menu.EXPORT);

				}
			}
		});
		
		
		tabHost.setCurrentTabByTag(getString(R.string.txt_home));
		setMenu(Menu.HOME);
		btnLogout.setOnClickListener(buttonClick);

	}

	private void addTab(int labelId, int drawableId, Intent intent) {
		TabHost.TabSpec spec = tabHost.newTabSpec(getString(labelId));

		View tabIndicator = createTabView(getApplicationContext(), labelId,
				drawableId);

		spec.setIndicator(tabIndicator);
		spec.setContent(intent);
		tabHost.addTab(spec);

	}

	private View createTabView(Context context, int lableId, int drawableId) {
		View view = LayoutInflater.from(context).inflate(
				R.layout.tabhost_feature, null, false);
		ImageView iv = (ImageView) view.findViewById(R.id.btn_feature_imv);
		iv.setImageResource(drawableId);
		TextView tv = (TextView) view.findViewById(R.id.btn_feature_tv);
		tv.setText(getString(lableId));
		return view;
	}

	private OnClickListener buttonClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.logout_menu:
				pre.putBoolean(Constants.PREFERENCE_REMEMBER_LOGIN, false);
				Intent startIntent = new Intent(SlidingActivity.this,
						MainActivity.class);
				startActivity(startIntent);
				finish();
				break;
			default:
				break;
			}
		}
	};

	public void init(int id) {
		inflater = LayoutInflater.from(this);
		view = inflater.inflate(id, null);
		this.setContentViewX(view);
	}

	@Override
	public void onBackPressed() {
		System.exit(0);
		super.onBackPressed();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			System.exit(0);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (getMenu()) {
		case SCANNER:
			ScannerActivity act =   (ScannerActivity)tabHost.getCurrentView().getContext();
			if(act != null)
			{
				act.onActivityResult(requestCode, resultCode, intent);
			}
//			Toast.makeText(
//					this,
//					"requestcode: " + requestCode + "\nresultcode: "
//							+ resultCode, Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
	}

	class GetListStudent extends AsyncTask<String, Void, Void> {
		private String meesage = "List class not available";
		private String malop = "";
		private ArrayList<Student> listSt = null;

		public GetListStudent(String malop) {
			this.malop = malop;
		}

		@Override
		protected Void doInBackground(String... params) {
			ListStudentReturnObject list = daApi.GetListStudent(malop);

			if (list != null) {
				listSt = list.getData();
				meesage = list.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Sau khi chay xong
			if (listSt != null && listSt.size() > 0) {

			} else {
				Toast.makeText(SlidingActivity.this, meesage, Toast.LENGTH_LONG)
						.show();
			}

		}

		@Override
		protected void onPreExecute() {
			// Make ProgressBar invisible

		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}

	}

}
